package com.mvp.shq.washer.ui.reg;

import com.mvp.shq.washer.entity.result.BaseResult;
import com.mvp.shq.washer.entity.TokenBean;
import com.mvp.shq.washer.entity.User;
import com.mvp.shq.washer.http.BaseObserver;
import com.mvp.shq.washer.utils.SignUtils;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/24.
 */

public class RegPresenter extends RegConstract.Presenter {
    @Override
    public void onStart() {

    }

    @Override
    void reg(String mobile, String pwd, String code) {
        String timestamp = SignUtils.getTime();
        pwd = StringUtils.MD5(pwd);
        Map<String,String> map = new HashMap();
        map.put("mobile",mobile);
        map.put("pwd",pwd);
        map.put("code",code);
        map.put("timestamp",timestamp);
        String sign = SignUtils.getSignature(map);
        model.reg(mobile,pwd,code,timestamp,sign)
                .subscribe(new BaseObserver<TokenBean>(view) {
                    @Override
                    protected void onSuccees(BaseResult<TokenBean> t) throws Exception {
                        if (t.isError()){
                            view.regFail(t.getMsg());
                        }else {
                            SpUtil.setToken(t.getData().getToken());
                            User user = new User();
                            user.setId(t.getData().getUserId());
                            SpUtil.setUser(user);
                            view.regSuccess();
                        }
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        view.regFail("注册失败:未知原因");
                    }
                });
    }

    @Override
    void code(String mobile) {
        model.getCode(mobile).subscribe(new BaseObserver<String>(view) {
            @Override
            protected void onSuccees(BaseResult<String> t) throws Exception {
                if (t.isError()){
                    view.getCodeFail(t.getMsg());
                }else {
                    view.getCodeSuccess();
                }
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                view.getCodeFail("获取失败:未知原因");
            }
        });
    }
}
